package com.ezerg.util;

import java.util.ResourceBundle;

public class ConfigUtil {
	ResourceBundle bundle = null;
	
	public ConfigUtil(String source) {
		// 加载配置文件
		bundle = ResourceBundle.getBundle(source);
		if (bundle == null) {
			throw new IllegalArgumentException("["+source+"] is not found!");
		}
	}
	
	public String getString(String bundleValue) {
		return getString(bundleValue, "");
	}
	
	public String getString(String bundleValue, String defaultValue) {
		if(bundle != null) {
			return parseString(bundle, bundleValue, defaultValue);
		} else {
			return "";
		}
	}
	
	public int getInt(String bundleValue, int defaultValue) {
		if(bundle != null) {
			return parseInt(bundle, bundleValue, defaultValue);
		} else {
			return 0;
		}
	}
	
	public boolean getBoolean(String bundleValue, boolean defaultValue) {
		if(bundle != null) {
			return parseBoolean(bundle, bundleValue, defaultValue);
		} else {
			return false;
		}
	}
	
	private int parseInt(ResourceBundle bundle, String bundleValue, int defaultValue) {
		String v = bundle.getString(bundleValue);
		try {
			return Integer.valueOf(v);
		} catch (Exception e) {
			return defaultValue;
		}
	}
	
	private String parseString(ResourceBundle bundle, String bundleValue, String defaultValue) {
		String v = bundle.getString(bundleValue);
		if(v == null || v.equals("")) {
			v = defaultValue;
		}
		return v;
	}
	
	private boolean parseBoolean(ResourceBundle bundle, String bundleValue, boolean defaultValue) {
		String v = bundle.getString(bundleValue);
		try {
			return Boolean.valueOf(v);
		} catch (Exception e) {
			return defaultValue;
		}
	}
}
